package com.jodinfo.outmirror.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

// Referenced classes of package com.hero.core.util:
//            UnsafeStringWriter

public final class StringUtils
{

    public static boolean isBlank(String str)
    {
        return str == null || str.length() == 0;
    }

    public static boolean isEmpty(String str)
    {
        return str == null || str.length() == 0;
    }

    public static boolean isNotEmpty(String str)
    {
        return str != null && str.trim().length() > 0;
    }

    public static boolean isEquals(String s1, String s2)
    {
        if(s1 == null && s2 == null)
            return true;
        if(s1 == null || s2 == null)
            return false;
        else
            return s1.equals(s2);
    }

    public static boolean isChanged(String oldS, String newS)
    {
        if(isEmpty(oldS) && isEmpty(newS))
            return false;
        if(isEmpty(oldS) || isEmpty(newS))
            return true;
        else
            return !oldS.equals(newS);
    }

    public static boolean isInteger(String str)
    {
        if(str == null || str.length() == 0)
            return false;
        else
            return INT_PATTERN.matcher(str).matches();
    }

    public static int parseInteger(String str)
    {
        if(!isInteger(str))
            return 0;
        else
            return Integer.parseInt(str);
    }

    public static boolean isJavaIdentifier(String s)
    {
        if(s.length() == 0 || !Character.isJavaIdentifierStart(s.charAt(0)))
            return false;
        for(int i = 1; i < s.length(); i++)
            if(!Character.isJavaIdentifierPart(s.charAt(i)))
                return false;

        return true;
    }

    public static boolean isContains(String values[], String value)
    {
        if(value != null && value.length() > 0 && values != null && values.length > 0)
        {
            String arr$[] = values;
            int len$ = arr$.length;
            for(int i$ = 0; i$ < len$; i$++)
            {
                String v = arr$[i$];
                if(value.equals(v))
                    return true;
            }

        }
        return false;
    }

    public static boolean isNumeric(String str)
    {
        if(str == null)
            return false;
        int sz = str.length();
        for(int i = 0; i < sz; i++)
            if(!Character.isDigit(str.charAt(i)))
                return false;

        return true;
    }

    public static String translat(String src, String from, String to)
    {
        if(isEmpty(src))
            return src;
        StringBuilder sb = null;
        int i = 0;
        for(int len = src.length(); i < len; i++)
        {
            char c = src.charAt(i);
            int ix = from.indexOf(c);
            if(ix == -1)
            {
                if(sb != null)
                    sb.append(c);
                continue;
            }
            if(sb == null)
            {
                sb = new StringBuilder(len);
                sb.append(src, 0, i);
            }
            if(ix < to.length())
                sb.append(to.charAt(ix));
        }

        return sb != null ? sb.toString() : src;
    }

    public static String[] split(String str, char ch)
    {
        List list = splitList(str, ch);
        return list != null ? (String[])(String[])list.toArray(EMPTY_STRING_ARRAY) : EMPTY_STRING_ARRAY;
    }

    public static List splitList(String str, char ch)
    {
        if(isBlank(str))
            return new ArrayList();
        if(!str.contains((new StringBuilder()).append(ch).append("").toString()))
        {
            List res = new ArrayList();
            res.add(str);
            return res;
        }
        List list = null;
        int ix = 0;
        int len = str.length();
        for(int i = 0; i < len; i++)
        {
            char c = str.charAt(i);
            if(c != ch)
                continue;
            if(list == null)
                list = new ArrayList();
            list.add(str.substring(ix, i));
            ix = i + 1;
        }

        if(ix > 0)
            list.add(str.substring(ix));
        return ((List) (list != null ? list : new ArrayList(0)));
    }

    public static String join(String array[])
    {
        if(array.length == 0)
            return "";
        StringBuilder sb = new StringBuilder();
        String arr$[] = array;
        int len$ = arr$.length;
        for(int i$ = 0; i$ < len$; i$++)
        {
            String s = arr$[i$];
            sb.append(s);
        }

        return sb.toString();
    }

    public static String join(String array[], char split)
    {
        if(array.length == 0)
            return "";
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < array.length; i++)
        {
            if(i > 0)
                sb.append(split);
            sb.append(array[i]);
        }

        return sb.toString();
    }

    public static String join(String array[], String split)
    {
        if(array.length == 0)
            return "";
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < array.length; i++)
        {
            if(i > 0)
                sb.append(split);
            sb.append(array[i]);
        }

        return sb.toString();
    }

    public static String join(Collection coll, String split)
    {
        if(coll.isEmpty())
            return "";
        StringBuilder sb = new StringBuilder();
        boolean isFirst = true;
        String s;
        for(Iterator i$ = coll.iterator(); i$.hasNext(); sb.append(s))
        {
            s = (String)i$.next();
            if(isFirst)
                isFirst = false;
            else
                sb.append(split);
        }

        return sb.toString();
    }

    private static Map parseKeyValuePair(String str, String itemSeparator)
    {
        String tmp[] = str.split(itemSeparator);
        Map map = new HashMap(tmp.length);
        for(int i = 0; i < tmp.length; i++)
        {
            Matcher matcher = KVP_PATTERN.matcher(tmp[i]);
            if(matcher.matches())
                map.put(matcher.group(1), matcher.group(2));
        }

        return map;
    }

    public static String getQueryStringValue(String qs, String key)
    {
        Map map = parseQueryString(qs);
        return (String)map.get(key);
    }

    public static Map parseQueryString(String qs)
    {
        if(qs == null || qs.length() == 0)
            return new HashMap();
        else
            return parseKeyValuePair(qs.replaceAll("\\?", "\\&"), "\\&");
    }

    public static String toQueryString(Map ps)
    {
        StringBuilder buf = new StringBuilder();
        if(ps != null && ps.size() > 0)
        {
            Iterator i$ = (new TreeMap(ps)).entrySet().iterator();
            do
            {
                if(!i$.hasNext())
                    break;
                java.util.Map.Entry entry = (java.util.Map.Entry)i$.next();
                String key = (String)entry.getKey();
                String value = (String)entry.getValue();
                if(key != null && key.length() > 0 && value != null && value.length() > 0)
                {
                    if(buf.length() > 0)
                        buf.append("&");
                    buf.append(key);
                    buf.append("=");
                    buf.append(value);
                }
            } while(true);
        }
        return buf.toString();
    }

    public static String camelToSplitName(String camelName, String split)
    {
        if(camelName == null || camelName.length() == 0)
            return camelName;
        StringBuilder buf = null;
        for(int i = 0; i < camelName.length(); i++)
        {
            char ch = camelName.charAt(i);
            if(ch >= 'A' && ch <= 'Z')
            {
                if(buf == null)
                {
                    buf = new StringBuilder();
                    if(i > 0)
                        buf.append(camelName.substring(0, i));
                }
                if(i > 0)
                    buf.append(split);
                buf.append(Character.toLowerCase(ch));
                continue;
            }
            if(buf != null)
                buf.append(ch);
        }

        return buf != null ? buf.toString() : camelName;
    }

    public static boolean equals(String str1, String str2)
    {
        if(str1 == null)
            return str2 == null;
        else
            return str1.equals(str2);
    }

    public static boolean equalsIgnoreCase(String str1, String str2)
    {
        if(str1 == null)
            return str2 == null;
        else
            return str1.equalsIgnoreCase(str2);
    }

    private StringUtils()
    {
    }

    private static String getZeroLen(int len)
    {
        String str = "";
        for(int i = 0; i < len; i++)
            str = (new StringBuilder()).append(str).append("0").toString();

        return str;
    }

    public static String comdify(String value)
    {
        DecimalFormat df = null;
        if(value.indexOf(".") > 0)
        {
            int i = value.length() - value.indexOf(".") - 1;
            switch(i)
            {
            case 0: // '\0'
                df = new DecimalFormat("###,##0");
                break;

            case 1: // '\001'
                df = new DecimalFormat("###,##0.0");
                break;

            case 2: // '\002'
                df = new DecimalFormat("###,##0.00");
                break;

            case 3: // '\003'
                df = new DecimalFormat("###,##0.000");
                break;

            case 4: // '\004'
                df = new DecimalFormat("###,##0.0000");
                break;

            default:
                df = new DecimalFormat("###,##0.00000");
                break;
            }
        } else
        {
            df = new DecimalFormat("###,##0");
        }
        double number = 0.0D;
        try
        {
            number = Double.parseDouble(value);
        }
        catch(Exception e)
        {
            number = 0.0D;
        }
        return df.format(number);
    }

    public static String getNumber(Object value, Object isShowComdify, Object decimalValue, Object coinValue)
    {
        if(value == null)
            return "";
        String val = value.toString();
        if(isShowComdify != null)
        {
            boolean result = Boolean.valueOf(isShowComdify.toString()).booleanValue();
            Double douvalue = Double.valueOf(Double.parseDouble(val));
            DecimalFormat df = new DecimalFormat("");
            val = df.format(douvalue);
            if(!result)
                val = val.replace(",", "");
        }
        if(decimalValue != null)
        {
            int len = Integer.parseInt(decimalValue.toString());
            if(len > 0)
            {
                int idx = val.indexOf(".");
                if(idx == -1)
                {
                    val = (new StringBuilder()).append(val).append(".").append(getZeroLen(len)).toString();
                } else
                {
                    String intStr = val.substring(0, val.indexOf("."));
                    String decimal = val.substring(val.indexOf(".") + 1);
                    if(decimal.length() > len)
                    {
                        Double douvalue = Double.valueOf(Double.parseDouble(val.replace(",", "")));
                        DecimalFormat df = new DecimalFormat("");
                        df.setMaximumFractionDigits(len);
                        String tmp = df.format(douvalue);
                        if(tmp.indexOf(".") == -1)
                        {
                            val = (new StringBuilder()).append(intStr).append(".").append(getZeroLen(len)).toString();
                        } else
                        {
                            decimal = tmp.substring(tmp.indexOf(".") + 1);
                            val = (new StringBuilder()).append(intStr).append(".").append(decimal).toString();
                        }
                    } else
                    if(decimal.length() < len)
                    {
                        int tmp = len - decimal.length();
                        val = (new StringBuilder()).append(val).append(getZeroLen(tmp)).toString();
                    }
                }
            }
        }
        if(coinValue != null)
            val = (new StringBuilder()).append(coinValue.toString()).append(val).toString();
        return val;
    }

    public static String trimSufffix(String toTrim, String trimStr)
    {
        for(; toTrim.endsWith(trimStr); toTrim = toTrim.substring(0, toTrim.length() - trimStr.length()));
        return toTrim;
    }

    public static String trimPrefix(String toTrim, String trimStr)
    {
        for(; toTrim.startsWith(trimStr); toTrim = toTrim.substring(trimStr.length()));
        return toTrim;
    }

    public static String trim(String toTrim, String trimStr)
    {
        return trimSufffix(trimPrefix(toTrim, trimStr), trimStr);
    }

    public static String trim(String str)
    {
        return str == null ? null : str.trim();
    }

    public static String replaceAll(String toReplace, String replace, String replaceBy)
    {
        replaceBy = replaceBy.replaceAll("\\$", "\\\\\\$");
        return toReplace.replaceAll(replace, replaceBy);
    }

    public static String substringBefore(String sourceStr, char beforeStr)
    {
        String strs[] = split(sourceStr, beforeStr);
        if(strs != null && strs.length > 0)
            return strs[0];
        else
            return null;
    }

    public static String createResponseMsg2(List successIds, List failIds)
    {
        StringBuffer msgSb = new StringBuffer();
        if(!successIds.isEmpty())
        {
            for(int i = 0; i < successIds.size(); i++)
                if(i == 0)
                {
                    msgSb.append((String)successIds.get(i));
                } else
                {
                    msgSb.append(",");
                    msgSb.append((String)successIds.get(i));
                }

            msgSb.append("\u64CD\u4F5C\u6210\u529F\uFF01");
        } else
        {
            msgSb.append("0\u4E2A\u64CD\u4F5C\u6210\u529F\uFF01");
        }
        if(!failIds.isEmpty())
        {
            for(int j = 0; j < failIds.size(); j++)
                if(j == 0)
                {
                    msgSb.append((String)failIds.get(j));
                } else
                {
                    msgSb.append(",");
                    msgSb.append((String)failIds.get(j));
                }

            msgSb.append("\u64CD\u4F5C\u5931\u8D25\uFF01");
        } else
        {
            msgSb.append("0\u4E2A\u64CD\u4F5C\u5931\u8D25\uFF01");
        }
        return msgSb.toString();
    }

    public static int strToInt(String str)
    {
        if(str == null || str.isEmpty())
            return 0;
        int rs = 0;
        try
        {
            rs = Integer.parseInt(str);
        }
        catch(Exception e)
        {
            rs = 0;
        }
        return rs;
    }

    public static String Html2Text(String inputString)
    {
        if(isEmpty(inputString))
            return "";
        String htmlStr = inputString;
        String textStr = "";
        try
        {
            String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>";
            String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>";
            String regEx_html = "<[^>]+>";
            Pattern p_script = Pattern.compile(regEx_script, 2);
            Matcher m_script = p_script.matcher(htmlStr);
            htmlStr = m_script.replaceAll("");
            Pattern p_style = Pattern.compile(regEx_style, 2);
            Matcher m_style = p_style.matcher(htmlStr);
            htmlStr = m_style.replaceAll("");
            Pattern p_html = Pattern.compile(regEx_html, 2);
            Matcher m_html = p_html.matcher(htmlStr);
            htmlStr = m_html.replaceAll("");
            htmlStr = htmlStr.replaceAll("&nbsp;", "");
            textStr = htmlStr;
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return textStr;
    }

    public static String getMinus(String num)
    {
        if(isEmpty(num))
            return "0";
        int numInt = 0;
        try
        {
            numInt = Integer.parseInt(num);
        }
        catch(NumberFormatException e)
        {
            numInt = 0;
        }
        return String.valueOf(numInt * -1);
    }

    public static String capitalize(String str)
    {
        return org.apache.commons.lang3.StringUtils.capitalize(str);
    }

    public static String uncapitalize(String str)
    {
        return org.apache.commons.lang3.StringUtils.uncapitalize(str);
    }

    public static String amountSubtraction(String amount1, String amount2)
    {
        int amount1Int = strToInt(amount1);
        int amount2Int = strToInt(amount2);
        int rs = amount1Int - amount2Int;
        return String.valueOf(rs);
    }

    public static String amountPlus(String amount1, String amount2)
    {
        int amount1Int = strToInt(amount1);
        int amount2Int = strToInt(amount2);
        int rs = amount1Int + amount2Int;
        return String.valueOf(rs);
    }

    public static int amountCompare(String amount1, String amount2)
    {
        int amount1Int = strToInt(amount1);
        int amount2Int = strToInt(amount2);
        if(amount1Int > amount2Int)
            return 1;
        return amount1Int >= amount2Int ? 0 : -1;
    }

    public static List getIdList(String ids)
    {
        List idList = new ArrayList();
        if(ids == null || ids.isEmpty())
            return idList;
        String idArray[] = ids.split(",");
        String arr$[] = idArray;
        int len$ = arr$.length;
        for(int i$ = 0; i$ < len$; i$++)
        {
            String id = arr$[i$];
            idList.add(new BigInteger(id));
        }

        return idList;
    }

    public static List getItemList(String items)
    {
        List rsList = new ArrayList();
        if(items == null || items.isEmpty())
            return rsList;
        String itemArray[] = items.split(",");
        String arr$[] = itemArray;
        int len$ = arr$.length;
        for(int i$ = 0; i$ < len$; i$++)
        {
            String item = arr$[i$];
            rsList.add(item);
        }

        return rsList;
    }

    public static List getBigIntegerItemList(String items)
    {
        List rsList = new ArrayList();
        if(items == null || items.isEmpty())
            return rsList;
        String itemArray[] = items.split(",");
        String arr$[] = itemArray;
        int len$ = arr$.length;
        for(int i$ = 0; i$ < len$; i$++)
        {
            String item = arr$[i$];
            rsList.add(new BigInteger(item));
        }

        return rsList;
    }

    public static boolean isEqualIgnoreBlank(String str1, String str2)
    {
        if(isEmpty(str1) && isEmpty(str2))
            return true;
        if(!isEmpty(str1) && isEmpty(str2))
            return false;
        if(isEmpty(str1) && isEmpty(str2))
            return false;
        else
            return str1.equals(str2);
    }

    public static List convertStrIds(String ids[])
    {
        List idList = new ArrayList();
        if(ids == null || ids.length == 0)
            return idList;
        String arr$[] = ids;
        int len$ = arr$.length;
        for(int i$ = 0; i$ < len$; i$++)
        {
            String id = arr$[i$];
            idList.add(new BigInteger(id));
        }

        return idList;
    }

    public static String encodeBase64(String str)
    {
        Base64 base64 = new Base64();
        try
        {
            str = base64.encodeToString(str.getBytes("UTF-8"));
        }
        catch(UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
        return str;
    }

    public static String decodeBase64(String str)
    {
        return str = new String(Base64.decodeBase64(str));
    }

    public static final String EMPTY = "";
    public static final String EMPTY_STRING_ARRAY[] = new String[0];
    private static final Pattern KVP_PATTERN = Pattern.compile("([_.a-zA-Z0-9][-_.a-zA-Z0-9]*)[=](.*)");
    private static final Pattern INT_PATTERN = Pattern.compile("^\\d+$");

   public static String getBytes(MultipartFile file){  
        
        byte[] buffer = null;
        if (file == null){
            return "";
        } else {             
            try {     
               CommonsMultipartFile cf= (CommonsMultipartFile)file; 
               DiskFileItem fi = (DiskFileItem)cf.getFileItem(); 
               File f = fi.getStoreLocation();
                FileInputStream fis = new FileInputStream(f);  
                ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);  
                byte[] b = new byte[1000];  
                int n;  
                while ((n = fis.read(b)) != -1) {  
                    bos.write(b, 0, n);  
                }  
                fis.close();  
                bos.close();  
                buffer = bos.toByteArray();  
            } catch (FileNotFoundException e) {  
                e.printStackTrace();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }
            
        }
          
         return new String(buffer);  
  }   
   
   /**
    * 密码翻译
    * TODO（方法详细描述说明、方法参数的具体涵义）
    * @author zhuxiaoliu
    * @date 2017年6月12日 上午10:44:37
    * @param str
    * @return
    */
   public static String encoderByMd5(String str){
		byte[] secretBytes = null;
		try {
			secretBytes = MessageDigest.getInstance("md5").digest(str.getBytes());
			} catch (NoSuchAlgorithmException e) {
				throw new RuntimeException("error happens", e);
				}
		return new BigInteger(1, secretBytes).toString(16);
		}
}

